import json
import os
import re
from datetime import datetime
from docx import Document
from docx.text.paragraph import Paragraph
from docx.table import Table


def read_docx_tables(docx_file):
    doc = Document(docx_file)
    document_data = {
        "version": "1.0",
        "document": os.path.basename(docx_file),
        "sections": [],
        "generated_at": datetime.now().isoformat()
    }

    current_section = None
    current_subsection = None
    current_table_title = None
    in_chapter3 = False

    chapter_map = {
        "1.服务概述": "chapter1",
        "2.服务规划": "chapter2",
        "3.服务设计": "chapter3"
    }

    elements = list(doc.element.body.iterchildren())

    for idx, element in enumerate(elements):
        # 处理段落
        if element.tag.endswith('p'):
            para = Paragraph(element, doc)
            text = para.text.strip()

            # 处理章节标题
            if text in chapter_map:
                current_section = {
                    "title": text,
                    "subsections": [],
                    "tables": []
                }
                document_data["sections"].append(current_section)
                in_chapter3 = (text == "3.服务设计")
                current_subsection = None  # 切换章节时重置子章节
                continue

            # 前两章处理子章节
            if current_section and not in_chapter3:
                if re.match(r'^\d+\.\d+', text):  # 匹配数字.数字开头的标题
                    current_subsection = {
                        "title": text,
                        "tables": []
                    }
                    current_section["subsections"].append(current_subsection)

            # 捕获表格标题（适用于所有章节）
            if idx + 1 < len(elements) and elements[idx + 1].tag.endswith('tbl'):
                current_table_title = text

        # 处理表格
        elif element.tag.endswith('tbl'):
            table_data = parse_table(element, doc)
            processed_table = None

            # 第三章特殊处理
            if in_chapter3:
                processed_table = process_chapter3_table(table_data, current_table_title)
            else:
                processed_table = process_general_table(table_data)

            # 确定存储位置
            if current_subsection:
                current_subsection["tables"].append(processed_table)
            elif current_section:
                current_section["tables"].append(processed_table)

            current_table_title = None  # 重置表格标题

    output_path = os.path.join(
        os.path.dirname(docx_file),
        f"{os.path.splitext(os.path.basename(docx_file))[0]}_output.json"
    )

    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(document_data, f, ensure_ascii=False, indent=2)

    return output_path


def parse_table(element, doc):
    """通用表格解析"""
    return [
        [cell.text.strip() for cell in row.cells]
        for row in Table(element, doc).rows
    ]


def process_general_table(table_data):
    """前两章通用处理器"""
    if not table_data:
        return {"table_type": "空表格"}

    # 自动识别表头
    headers = table_data[0]
    return {
        "table_type": "数据表",
        "headers": headers,
        "data": [
            dict(zip(headers, row))
            for row in table_data[1:] if any(cell for cell in row)
        ]
    }


def process_chapter3_table(table_data, title):
    """第三章智能处理器"""
    # 根据标题识别表格类型
    table_type = '其他表格'
    type_map = {
        r'基本信息$': '基本信息',
        r'请求头参数描述$': '请求头参数描述',
        r'请求参数描述$': '请求参数描述',
        r'返回参数$': '返回参数'
    }

    for pattern, name in type_map.items():
        if title and re.search(pattern, title):
            table_type = name
            break

    result = {"table_type": table_type}

    # 处理不同类型
    if table_type == '基本信息':
        result["data"] = {row[0]: row[1] for row in table_data if len(row) >= 2}
    elif table_type in type_map.values():
        headers = ['参数名', '类型', '必填', '描述'][:len(table_data[0])]
        result["data"] = [dict(zip(headers, row)) for row in table_data[1:]]
    else:
        # 复合表格处理
        if len(table_data) > 1 and len(table_data[0]) == len(table_data[1]):
            result.update({
                "table_type": "数据表",
                "headers": table_data[0],
                "data": [dict(zip(table_data[0], row)) for row in table_data[1:]]
            })
        else:
            result["raw_data"] = table_data

    # 示例JSON解析
    if '示例' in title:
        result.update(parse_json_example(table_data))

    return result


def parse_json_example(table_data):
    """解析JSON示例"""
    json_str = ''.join(cell for row in table_data for cell in row)
    try:
        return {"data": json.loads(json_str)}
    except:
        return {"raw_data": json_str}


# if __name__ == '__main__':
#     output_path = read_docx_tables('服务设计说明书.docx')
#     print(f"生成文件路径：{output_path}")